import request from '@/utils/request'
import type { FileInfo } from './file'

// 分享信息接口
export interface ShareInfo {
  id: number
  userId: number
  fileId: number
  shareCode: string
  shareName: string
  shareType: number
  permissions: number
  password?: string
  expireTime?: string
  visitCount: number
  downloadCount: number
  status: number
  createTime: string
  updateTime: string
  fileName?: string  // 分享列表接口不返回此字段
  viewCount?: number // 分享列表接口不返回此字段
}

// 分享列表查询参数
export interface ShareListParams {
  page?: number
  size?: number
  orderBy?: string
  orderType?: 'asc' | 'desc'
}

// 分享列表响应
export interface ShareListResponse {
  content: ShareInfo[]
  totalElements: number  // 后端返回的字段名
  number: number         // 后端返回的页码（从0开始）
  size: number
  totalPages: number     // 后端返回的字段名
  // 兼容字段
  total?: number
  page?: number
  pages?: number
}

// 创建分享参数
export interface CreateShareParams {
  fileId: number
  shareName: string
  permissions: number
  password?: string
  expireTimeStr?: string
}

// 分享访问响应
export interface ShareAccessResponse {
  shareId: number
  shareName: string
  permissions: number
  needPassword: boolean
  expireTime?: string
  visitCount: number
  downloadCount: number
  file: FileInfo
}

// 分享密码验证响应
export interface ShareVerifyResponse {
  verified: boolean
  file: FileInfo
}

// 创建分享
export const createShare = (params: CreateShareParams): Promise<ShareInfo> => {
  return request.post('/share/create', null, { params })
}

// 获取我的分享列表
export const getMyShareList = (params: ShareListParams): Promise<ShareListResponse> => {
  return request.get('/share/my/list', { params })
}

// 取消分享
export const cancelShare = (shareId: number): Promise<void> => {
  return request.post(`/share/${shareId}/cancel`)
}

// 更新分享设置
export const updateShare = (shareId: number, params: Partial<CreateShareParams>): Promise<ShareInfo> => {
  return request.post(`/share/${shareId}/update`, null, { params })
}

// 访问分享
export const getShare = (shareCode: string): Promise<ShareAccessResponse> => {
  return request.get(`/share/${shareCode}`)
}

// 验证分享密码
export const verifySharePassword = (shareCode: string, password: string): Promise<ShareVerifyResponse> => {
  return request.post(`/share/${shareCode}/verify`, null, {
    params: { password }
  })
}

// 记录分享下载
export const recordShareDownload = (shareCode: string): Promise<void> => {
  return request.post(`/share/${shareCode}/download`)
}